package org.ar.gameserver.common.socket;

import java.io.IOException;
import java.net.InetSocketAddress;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.SocketAcceptor;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.ar.gameserver.common.amf.AMF3CodecFactory;

public class ServerSocket {
	
	private SocketAcceptor acceptor;
	
	public ServerSocket() throws Exception {
		try {
			acceptor = new NioSocketAcceptor();
			
			acceptor.getFilterChain();
			DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
	        chain.addLast("amf3", new ProtocolCodecFilter(new AMF3CodecFactory()));
	        chain.addLast("logger", new LoggingFilter());
		} catch (Exception e) {
			throw e;
		}
	}
	
	public void start(IoHandlerAdapter ioHandler, int bindPort) throws Exception {
		try {
	        acceptor.setHandler(ioHandler);
	        acceptor.bind(new InetSocketAddress(bindPort));
		} catch (Exception e) {
			throw e;
		}
	}
	
	public void stop(int bindPort) {
		if(acceptor != null) {
			acceptor.unbind(new InetSocketAddress(bindPort));
		}
	}
}
